import React, { useState, useEffect } from 'react';
import { X, Search, Grid3X3, List, CheckCircle2 } from 'lucide-react';
import type { ComplianceItem } from '@/types/work';
import { ViewMode } from '@/types/work';
import { compareByTitle } from '@/utils/utils';

interface AssociationDialogProps {
  risk: ComplianceItem | null;
  guaranteeItems: ComplianceItem[];
  isOpen: boolean;
  onClose: () => void;
  onSave: (riskId: string, guaranteeIds: string[]) => void;
}

/**
 * 关联管理对话框组件
 * 提供详细的风险项与保障项关联管理界面
 */
const AssociationDialog: React.FC<AssociationDialogProps> = ({
  risk,
  guaranteeItems,
  isOpen,
  onClose,
  onSave
}) => {
  // 状态
  const [selectedGuaranteeIds, setSelectedGuaranteeIds] = useState<string[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [viewMode, setViewMode] = useState<ViewMode>(ViewMode.GRID);
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 8;
  
  // 当风险项变化时，更新选中的保障项
  useEffect(() => {
    if (risk) {
      setSelectedGuaranteeIds(risk.related_guarantees || []);
    } else {
      setSelectedGuaranteeIds([]);
    }
  }, [risk]);
  
  // 如果对话框未打开，不渲染内容
  if (!isOpen || !risk) {
    return null;
  }
  
  // 根据搜索词过滤保障项并排序
  const filteredGuaranteeItems = guaranteeItems
    .filter(item =>
      item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.description.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .sort((a, b) => {
      // 首先按是否已关联排序
      const aSelected = selectedGuaranteeIds.includes(a.id);
      const bSelected = selectedGuaranteeIds.includes(b.id);
      if (aSelected !== bSelected) {
        return aSelected ? -1 : 1;
      }
      // 其次按标题排序
      return compareByTitle({title: a.title, description: a.description || ''}, {title: b.title, description: b.description || ''});
    });
  
  // 计算分页
  const totalPages = Math.ceil(filteredGuaranteeItems.length / itemsPerPage);
  const paginatedItems = filteredGuaranteeItems.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );
  
  // 处理保障项选择
  const handleGuaranteeToggle = (guaranteeId: string) => {
    setSelectedGuaranteeIds(prev => {
      if (prev.includes(guaranteeId)) {
        return prev.filter(id => id !== guaranteeId);
      } else {
        return [...prev, guaranteeId];
      }
    });
  };
  
  // 处理全选
  const handleSelectAll = () => {
    if (selectedGuaranteeIds.length === guaranteeItems.length) {
      setSelectedGuaranteeIds([]);
    } else {
      setSelectedGuaranteeIds(guaranteeItems.map(item => item.id));
    }
  };
  
  // 处理保存
  const handleSave = () => {
    onSave(risk.id, selectedGuaranteeIds);
    onClose();
  };
  
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
      <div className="bg-card rounded-lg shadow-lg w-full max-w-4xl max-h-[90vh] flex flex-col">
        {/* 对话框头部 */}
        <div className="flex justify-between items-center p-4 border-b border-border">
          <div>
            <h2 className="text-xl font-bold text-foreground">管理风险关联</h2>
            <p className="text-sm text-muted-foreground mt-1">{risk.title || '未命名风险项'}</p>
          </div>
          
          <button
            onClick={onClose}
            className="p-2 rounded-full hover:bg-muted transition-colors"
            aria-label="关闭"
          >
            <X className="h-5 w-5 text-muted-foreground" />
          </button>
        </div>
        
        {/* 风险项详情 */}
        <div className="p-4 bg-muted/30 border-b border-border">
          <div className="space-y-2">
            <div>
              <span className="text-sm font-medium text-muted-foreground">风险描述:</span>
              <p className="text-sm text-foreground mt-1 break-words whitespace-pre-wrap">
                {risk.description || '暂无描述'}
              </p>
            </div>
            <div>
              <span className="text-sm font-medium text-muted-foreground">检查人:</span>
              <p className="text-sm text-foreground mt-1 break-words">
                {risk.inspector || '未指定'}
              </p>
            </div>
          </div>
        </div>
        
        {/* 保障项选择 */}
        <div className="flex-1 overflow-hidden flex flex-col">
          {/* 搜索和视图切换 */}
          <div className="p-4 border-b border-border flex flex-col sm:flex-row justify-between gap-4">
            <div className="relative w-full sm:w-80">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <input
                type="text"
                placeholder="搜索保障项..."
                value={searchTerm}
                onChange={(e) => {
                  setSearchTerm(e.target.value);
                  setCurrentPage(1);
                }}
                className="w-full pl-10 pr-4 py-2 rounded-md border border-input bg-background text-sm"
              />
            </div>
            
            <div className="flex items-center space-x-4">
              <button
                onClick={handleSelectAll}
                className="px-3 py-1.5 rounded-md bg-secondary text-secondary-foreground hover:bg-secondary/80 transition-colors text-sm"
              >
                {selectedGuaranteeIds.length === guaranteeItems.length ? '取消全选' : '全选'}
              </button>
              
              <div className="flex items-center space-x-2">
                <span className="text-sm text-muted-foreground">视图:</span>
                <button
                  onClick={() => setViewMode(ViewMode.GRID)}
                  className={`p-1.5 rounded-md ${
                    viewMode === ViewMode.GRID
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-secondary text-secondary-foreground hover:bg-secondary/80'
                  }`}
                  aria-label="网格视图"
                >
                  <Grid3X3 className="h-4 w-4" />
                </button>
                
                <button
                  onClick={() => setViewMode(ViewMode.LIST)}
                  className={`p-1.5 rounded-md ${
                    viewMode === ViewMode.LIST
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-secondary text-secondary-foreground hover:bg-secondary/80'
                  }`}
                  aria-label="列表视图"
                >
                  <List className="h-4 w-4" />
                </button>
              </div>
            </div>
          </div>
          
          {/* 保障项列表 */}
          <div className="flex-1 overflow-y-auto p-4">
            {viewMode === ViewMode.GRID ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                {paginatedItems.map(guarantee => (
                  <div
                    key={guarantee.id}
                    onClick={() => handleGuaranteeToggle(guarantee.id)}
                    className={`p-3 rounded-lg border cursor-pointer transition-all duration-200 ${
                      selectedGuaranteeIds.includes(guarantee.id)
                        ? 'border-primary bg-primary/10 shadow-[0_0_0_1px_hsl(var(--primary))] dark:shadow-[0_0_0_1px_hsl(var(--primary))]'
                        : 'border-border hover:border-primary/50 hover:bg-accent/50'
                    }`}
                  >
                    <div className="flex items-start justify-between">
                      <h4 className={`font-medium line-clamp-1 ${
                        selectedGuaranteeIds.includes(guarantee.id)
                          ? 'text-primary font-semibold'
                          : 'text-foreground'
                      }`} title={guarantee.title || '未命名保障项'}>{guarantee.title || '未命名保障项'}</h4>
                      {selectedGuaranteeIds.includes(guarantee.id) && (
                        <CheckCircle2 className="h-4 w-4 text-primary flex-shrink-0" />
                      )}
                    </div>
                    <p className="text-xs text-muted-foreground mt-2">
                      检查人: <span className="break-words">{guarantee.inspector || '未指定'}</span>
                    </p>
                  </div>
                ))}
              </div>
            ) : (
              <div className="space-y-2">
                {paginatedItems.map(guarantee => (
                  <div
                    key={guarantee.id}
                    onClick={() => handleGuaranteeToggle(guarantee.id)}
                    className={`p-3 rounded-lg border cursor-pointer transition-all duration-200 ${
                      selectedGuaranteeIds.includes(guarantee.id)
                        ? 'border-primary bg-primary/10 shadow-[0_0_0_1px_hsl(var(--primary))] dark:shadow-[0_0_0_1px_hsl(var(--primary))]'
                        : 'border-border hover:border-primary/50 hover:bg-accent/50'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className={`font-medium ${
                          selectedGuaranteeIds.includes(guarantee.id)
                            ? 'text-primary font-semibold'
                            : 'text-foreground'
                        }`}>{guarantee.title || '未命名保障项'}</h4>
                        <p className="text-xs text-muted-foreground mt-1">
                          检查人: <span className="break-words">{guarantee.inspector || '未指定'}</span>
                        </p>
                      </div>
                      <div className="ml-4 flex-shrink-0">
                        {selectedGuaranteeIds.includes(guarantee.id) ? (
                          <CheckCircle2 className="h-5 w-5 text-primary animate-in fade-in duration-200" />
                        ) : (
                          <div className="w-5 h-5 rounded-full border-2 border-muted-foreground" />
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
          
          {/* 分页 */}
          {totalPages > 1 && (
            <div className="p-4 border-t border-border flex justify-between items-center">
              <div className="text-sm text-muted-foreground">
                已选择 {selectedGuaranteeIds.length} 项保障
              </div>
              
              <div className="flex space-x-1">
                <button
                  onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                  disabled={currentPage === 1}
                  className="px-2 py-1 rounded-md border border-input bg-background text-foreground hover:bg-accent disabled:opacity-50 disabled:pointer-events-none"
                >
                  上一页
                </button>
                
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  // 计算要显示的页码范围
                  let startPage = Math.max(1, currentPage - 2);
                  let endPage = Math.min(totalPages, startPage + 4);
                  
                  // 如果范围不够5页，调整起始页
                  if (endPage - startPage < 4) {
                    startPage = Math.max(1, endPage - 4);
                  }
                  
                  const pageNumber = startPage + i;
                  if (pageNumber <= endPage) {
                    return (
                      <button
                        key={pageNumber}
                        onClick={() => setCurrentPage(pageNumber)}
                        className={`w-8 h-8 flex items-center justify-center rounded-md ${
                          currentPage === pageNumber 
                            ? 'bg-primary text-primary-foreground' 
                            : 'border border-input bg-background text-foreground hover:bg-accent'
                        }`}
                      >
                        {pageNumber}
                      </button>
                    );
                  }
                  return null;
                })}
                
                <button
                  onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                  disabled={currentPage === totalPages}
                  className="px-2 py-1 rounded-md border border-input bg-background text-foreground hover:bg-accent disabled:opacity-50 disabled:pointer-events-none"
                >
                  下一页
                </button>
              </div>
            </div>
          )}
        </div>
        
        {/* 对话框底部 */}
        <div className="p-4 border-t border-border flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-md bg-secondary text-secondary-foreground hover:bg-secondary/80 transition-colors"
          >
            取消
          </button>
          
          <button
            onClick={handleSave}
            className="px-4 py-2 rounded-md bg-primary text-primary-foreground hover:bg-primary-hover transition-colors"
          >
            保存关联
          </button>
        </div>
      </div>
    </div>
  );
};

export default AssociationDialog;
